<script setup>
import { ref, reactive, onMounted, unref, watch, computed } from 'vue'
import { useCorePage } from '@/composables/open-link.js'
import { formatColumn } from '@/utils/tools.js'
import PreauthorizationApplication from './PreauthorizationApplication.vue'
import { storeToRefs } from 'pinia'
import useAppStore from '@/stores/app'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const appStore = useAppStore()
const { language } = storeToRefs(appStore)
import {
  queryPreAuth,
  downloadAuthAttachment,
  downloadPreAuthApproved,
  postUrgentReason
} from '@/api/home'
import { useAccountStore } from '@/stores/account'
import { downloadFile } from '@/utils/file'
import { getByDictType } from '@/api/common'
import { message as AMessage } from 'ant-design-vue'

const props = defineProps({
  policyInfo: {
    type: Object
  },
  insuredInfo: {
    type: Object
  }
})
const accountStore = useAccountStore()
const isEyeOpen = computed(() => {
  return accountStore.DESENSITIZATION
})
// 脱敏
watch(
  () => isEyeOpen.value,
  (newValue, oldValue) => {
    getTableList()
  }
)
// 切换被保人
watch(
  () => props.policyInfo.customer_id,
  (newValue, oldValue) => {
    initData()
  }
)

const prAutheOpen = ref(false)
const activeYear = ref(props.policyInfo.policyYear)
const options = ref([])
const pageFrom = ref('personal') // 1:个人中心进入；2:医院预授权页面
// 从2007年开始循环到当前年份后两年
const currentYear = new Date().getFullYear()
for (let year = currentYear + 2; year >= 2007; year--) {
  options.value.push({
    value: `${year}`,
    label: `${year}`
  })
}

function handlePageChange(page, pageSize) {
  pagination.current = page
  pagination.pageSize = pageSize
  getTableList()
}
const pagination = reactive({
  current: 1,
  pageSize: 10,
  size: 'large',
  showSizeChanger: true,
  hideOnSinglePage: true,
  total: 0,
  onChange: handlePageChange
})
const dynamicColumns = computed(() => {
  return [
    {
      title: t('home.preAuth.PreAuthNo'),
      dataIndex: 'preAuthNumber',
      key: 'preAuthNumber',
      width: 120,
      customRender: ({ text, record, index }) => formatColumn(text)
    },
    {
      title: t('home.preAuth.ServiceType'),
      dataIndex: 'serviceType',
      key: 'serviceType',
      width: 140,
      customRender: ({ text, record, index }) => formatColumn(text)
    },
    {
      title: t('home.preAuth.PatientName'),
      dataIndex: 'name',
      key: 'name',
      width: 160,
      customRender: ({ text, record, index }) => formatColumn(text)
    },
    {
      title: t('home.preAuth.PreAuthStatus'),
      dataIndex: 'preAuthStatus',
      key: 'preAuthStatus',
      width: 140,
      customRender: ({ text, record, index }) => formatColumn(text)
    },
    {
      title: t('home.preAuth.ApplicationDate'),
      dataIndex: 'applyDate',
      key: 'applyDate',
      width: 120,
      customRender: ({ text, record, index }) => formatColumn(text)
    },
    {
      title: t('home.preAuth.ApplicationHospital'),
      dataIndex: 'appliedProviderName',
      key: 'appliedProviderName',
      width: 180,
      customRender: ({ text, record, index }) => formatColumn(text)
    },
    {
      title: t('home.preAuth.ServiceDate'),
      dataIndex: 'serviceDate',
      key: 'serviceDate',
      width: 160,
      customRender: ({ text, record, index }) => formatColumn(text)
    },
    {
      title: t('home.preAuth.RequestedAmount'),
      dataIndex: 'applyAmount',
      key: 'applyAmount',
      width: 160,
      customRender: ({ text, record, index }) => formatColumn(text)
    },
    {
      title: t('home.preAuth.ApprovedAmount'),
      dataIndex: 'approvedAmount',
      key: 'approvedAmount',
      width: 120,
      customRender: ({ text, record, index }) => formatColumn(text)
    },
    {
      title: t('home.preAuth.Operator'),
      dataIndex: 'processor',
      key: 'processor',
      width: 120,
      customRender: ({ text, record, index }) => formatColumn(text)
    },
    {
      title: t('global.action'),
      dataIndex: 'action',
      key: 'action',
      width: language.value == 'zh' ? 140 : 220,
      fixed: 'right'
    }
  ]
})
let loading = ref(false)
let dataSource = ref([])
async function getTableList() {
  loading.value = true
  const data = {
    current: pagination.current,
    size: pagination.pageSize,
    desensitization: unref(isEyeOpen) ? '02' : '01',
    model: {
      memberID: props.policyInfo.member_id,
      customerID: props.policyInfo.customer_id,
      policyYear: unref(activeYear)
    }
  }
  let res = null
  try {
    res = await queryPreAuth(data)
  } catch (err) {
    console.log('err', err)
  } finally {
    loading.value = false
  }
  if (res?.isSuccess) {
    const list = res.data.records
    list.forEach((ele) => {
      ele.popoverVisible = false
      ele.attachmentLoading = false
      ele.approvedLoading = false
    })
    dataSource.value = list
    pagination.total = Number(res.data.total)
  }
}
async function initData() {
  pagination.current = 1
  pagination.pageSize = 10
  getTableList()
}
let reasonList = ref([])
let urgentReason = ref(null)
async function getReasonList() {
  let res = await getByDictType({ dictType: 'urgentreason' })
  // console.log('res', res)
  if (res.isSuccess) {
    const list = []
    res.data &&
      res.data.length &&
      res.data.map((v) => {
        list.push({
          label: v.dictName,
          value: v.dictCode
        })
      })
    reasonList.value = list
  }
}
// open popover 加急原因置为初始化
function popoverChange(visible) {
  if (visible) {
    urgentReason.value = null
  }
}
async function confirmUrgent(record) {
  if (!unref(urgentReason)) {
    AMessage.warning('请选择加急原因')
    return
  }
  const data = {
    urgentReason: unref(urgentReason),
    preAuthNumber: record.preAuthNumber
  }
  let res = await postUrgentReason(data)
  console.log('res', res)
  if (res?.isSuccess) {
    AMessage.success('加急成功。')
    record.popoverVisible = false
  }
}
onMounted(async () => {
  initData()
  getReasonList()
})
function handleChange() {
  initData()
}

async function downloadPreAuthFile(record) {
  record.attachmentLoading = true
  const params = {
    preAuthNumber: record.preAuthNumber
  }
  let res = null
  try {
    res = await downloadAuthAttachment(params)
  } catch (err) {
    console.log('err', err)
  } finally {
    record.attachmentLoading = false
  }
  if (res) {
    downloadFile(res)
    AMessage.success('下载成功')
  }
}
async function downloadPreAuthLetter(record) {
  if (record.preAuthStatus != '已通过') return
  record.approvedLoading = true

  const params = {
    preAuthNumber: record.preAuthNumber
  }
  let res = null
  try {
    res = await downloadPreAuthApproved(params)
  } catch (err) {
    console.log('err', err)
  } finally {
    record.approvedLoading = false
  }
  if (res) {
    downloadFile(res)
    AMessage.success('下载成功')
  }
}
function getPopupContainer(triggerNode) {
  return triggerNode.parentNode.parentNode.parentNode.parentNode
}
function openPreAuth() {
  prAutheOpen.value = true
}
function close() {
  prAutheOpen.value = false
}
</script>
<template>
  <div>
    <div class="pre-auth">
      <div class="common-info-header">
        <span class="common-info-header-name"> {{ $t('home.preAuth.PreAuthInfo') }} </span>
        <a-select
          ref="select"
          class="mr-20"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
          v-model:value="activeYear"
          style="width: 138px"
          :options="options"
          @change="handleChange"
        >
        </a-select>
        <div class="line"></div>
        <div class="link" @click="openPreAuth">
          <svg-icon size="14" name="pre-auth" />
          {{ $t('home.preAuth.PreAuthRequest') }}
        </div>
      </div>
      <div class="pre-auth-main">
        <a-table
          :loading="loading"
          :pagination="pagination"
          :scroll="{ x: 1920 }"
          class="ant-table-striped"
          :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
          size="middle"
          :dataSource="dataSource"
          :columns="dynamicColumns"
        >
          <template #bodyCell="{ column, text, record }">
            <template v-if="column.key === 'preAuthNumber'">
              <span
                class="text-decortion"
                @click="
                  useCorePage({
                    preAuthNumber: record.preAuthNumber,
                    type: 'preAuth'
                  })
                "
                v-if="!record.flag"
              >
                {{ formatColumn(text) }}
              </span>
              <a-tooltip v-else :getPopupContainer="getPopupContainer">
                <template #title>
                  <div>加急人:{{ record.urgentOperator }}</div>
                  <div>加急部门:{{ record.urgentDepartment }}</div>
                  <div>加急原因:{{ record.urgentReason }}</div>
                </template>
                <span
                  class="text-decortion text-decortion-red"
                  @click="
                    useCorePage({
                      preAuthNumber: record.preAuthNumber,
                      type: 'preAuth'
                    })
                  "
                  >{{ formatColumn(text) }}
                </span>
              </a-tooltip>
            </template>
            <template v-if="column.key === 'preAuthStatus'">
              <span class="auth-status">
                <span>{{ formatColumn(text) }}</span>
                <a-tooltip
                  v-if="record.caseStatusCode == 10"
                  :getPopupContainer="getPopupContainer"
                  :overlayStyle="{ maxWidth: '500px' }"
                >
                  <template #title>
                    <p>担保函备注:</p>
                    <p>{{ record.gopremark }}</p>
                    <p>医学评估:</p>
                    <p>{{ record.medicalRemark }}</p>
                  </template>
                  <svg-icon size="14" name="home-query" />
                </a-tooltip>
              </span>
            </template>
            <template v-if="column.key === 'action'">
              <span v-if="record.caseStatusCode == 10" class="operation-disabled">
                {{ $t('home.preAuth.Expedite') }}
              </span>
              <a-popover
                trigger="click"
                :title="$t('home.preAuth.ExpediteReason')"
                v-model:open="record.popoverVisible"
                v-else
                :getPopupContainer="getPopupContainer"
                @openChange="popoverChange"
              >
                <template #content>
                  <a-select
                    ref="select"
                    v-model:value="urgentReason"
                    :placeholder="$t('global.PlaceholderSelect')"
                    style="width: 300px"
                    :options="reasonList"
                  >
                  </a-select>
                  <div class="reason-popover-btns">
                    <a-button @click="record.popoverVisible = false">{{
                      $t('global.cancel')
                    }}</a-button>
                    <a-button type="primary" @click="confirmUrgent(record)">{{
                      $t('global.confirm')
                    }}</a-button>
                  </div>
                </template>
                <span
                  class="table-operation"
                  @click="record.popoverVisible = !record.popoverVisible"
                >
                  {{ $t('home.preAuth.Expedite') }}</span
                >
              </a-popover>
              <span
                class="splice-line"
                :class="{ 'splice-line-disabled': record.caseStatusCode == 10 }"
              ></span>
              <a-spin wrapperClassName="file-spin" :spinning="record.approvedLoading" size="small">
                <span
                  class="table-operation"
                  :class="{ 'operation-disabled': record.preAuthStatus != '已通过' }"
                  @click="downloadPreAuthLetter(record)"
                  >{{ $t('home.preAuth.GOP') }}</span
                ></a-spin
              >
              <span
                class="splice-line"
                :class="{ 'splice-line-disabled': record.caseStatusCode == 10 }"
              ></span>
              <a-spin
                wrapperClassName="file-spin"
                :spinning="record.attachmentLoading"
                size="small"
              >
                <span class="table-operation cursor-pointer" @click="downloadPreAuthFile(record)">{{
                  $t('home.preAuth.Attachments')
                }}</span>
              </a-spin>
            </template>
          </template>
        </a-table>
      </div>
    </div>
    <PreauthorizationApplication
      v-if="prAutheOpen"
      :prAutheOpen="prAutheOpen"
      @close="close"
      :pageFrom="pageFrom"
      :policyInfo="props.policyInfo"
    />
  </div>
</template>
<style lang="scss">
.pre-auth {
  .ant-table-striped .table-striped td {
    background-color: #fafafa;
  }
  .ant-table-striped td,
  .ant-table-striped th {
    border-top: transparent !important;
    border-bottom: transparent !important;
  }
  &-main {
    padding: 20px 24px;
    margin-top: 20px;
    background: #ffffff;
    box-shadow: 0px 0px 6px 0px rgba(0, 58, 84, 0.08);
    border-radius: 10px;
    .file-spin {
      display: inline-block;
    }
    .auth-status {
      display: flex;
      align-items: center;
      position: relative;
      .svg-icon {
        margin-left: 5px;
        cursor: pointer;
        color: #999;
      }
    }
    .text-decortion {
      font-weight: 400;
      font-size: 14px;
      color: #4d789c;
      text-decoration: underline;
      cursor: pointer;
    }
    .text-decortion:hover {
      color: #97b7c5;
    }
    .text-decortion-red {
      color: #cf595d;
    }
  }

  .reason-popover-btns {
    display: flex;
    justify-content: end;
    margin-top: 12px;
    .ant-btn {
      margin-left: 10px;
    }
  }
}
</style>
